import {reqCartList,reqDeleteCart,reqCheckCart} from "@/api"
import { userTemp } from "@/utils/temp_token";
const state={
    userTempId: userTemp(),
    cartList:[]
}
const actions ={
    async getShopCartList({commit}){
          let result =  await reqCartList();
          if(result.code == 200){
            //   console.log(result.data[0])
                commit('GETSHOPCARTLIST',result.data)
          }
    },
    // 删除商品的方法
    async deleteShop({commit},skuId){
        let result = await reqDeleteCart(skuId);
        console.log(result)
        if(result.code == 200){
            return 'ok';
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 单选框调用的api接口返回的结果
    async updateChecked({commit},{skuId,isChecked}){
        let result = await reqCheckCart(skuId,isChecked);
        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 全选框设置方法
   async AllChecked({dispatch,getters},isChecked){
    //    用数组接收返回值  在进行判断
        let arr =[]
       getters.shopCartData.cartInfoList.forEach((item)=>{
            item.isChecked = isChecked;
            let promise = dispatch('updateChecked',{skuId:item.skuId,isChecked})
            arr.push(promise)
       }) 
    //    判断数组里面是不是全部是成功的Promise 如果有一个是失败的Promise 则返回失败的promise  全部成功才是返回成功promise
       return Promise.all(arr)
   },
    //  删除选中的商品
    async deleteCheck({dispatch,getters}){
        let arr =[]
        getters.shopCartData.cartInfoList.forEach((item)=>{
            if(item.isChecked == 1){
                let promise = dispatch('deleteShop',item.skuId)
                arr.push(promise)
            }
        })
        return Promise.all(arr);
    }
}
const mutations ={
    GETSHOPCARTLIST(state,cartList){
            state.cartList = cartList
    }
}
const getters = {
    shopCartData(state){
        return state.cartList[0] || {}
    }
}
export default{
    state,
    actions,
    mutations,
    getters
}